/*
Copyright (c) 2008 André Luiz Alves Moraes

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

package andre.grids.filesystem.server.directorymanagement;

import andre.grids.db.Database;
import andre.grids.db.DbDirectoryQueries;
import andre.grids.db.DbFileQueries;
import andre.grids.db.DbLogEntryQueries;
import andre.grids.db.DbPeerQueries;
import andre.grids.db.DbReplicaQueries;
import andre.grids.db.dataclasses.DbDirectory;
import andre.grids.db.dataclasses.DbFile;
import andre.grids.db.dataclasses.DbFileReplica;
import andre.grids.db.dataclasses.DbLogEntry;
import andre.grids.db.dataclasses.DbPeer;
import andre.grids.filesystem.common.DirectoryOperations;
import andre.grids.filesystem.common.exceptions.*;
import andre.grids.guids.IGuid;
import andre.grids.guids.IGuidFactory;
import andre.grids.util.PathUtils;
import java.rmi.RemoteException;
import java.util.Hashtable;
import  andre.grids.filesystem.server.configuration.*;
import andre.grids.network.FileServerTable;
import andre.grids.network.MasterPeerTable;
import andre.grids.network.PeerObjects;
import andre.grids.util.ByteToHexConverter;
import andre.grids.util.FastStringArray;
import andre.grids.util.Filters;
import andre.grids.util.log.*;

/**
 *
 * @author andre
 */
public class DirectoryOperationsImpl implements DirectoryOperations {
    
    private IGuidFactory guidFactory;

    public IGuidFactory getGuidFactory() {
        return guidFactory;
    }

    public void setGuidFactory(IGuidFactory guidFactory) {
        this.guidFactory = guidFactory;
    }
//    private IDirectoryManager manager;
    
    public DirectoryOperationsImpl() throws RemoteException 
    {
        DirectoryOperationsConfiguration.configure(this);
    }

    public void createDirectory(String path) throws RemoteException {
        String masterHostName = ConfigurationManager.getBaseConfigInstance().getValue(ServerConfigurationProps.SERVER_HOST_NAME);
        if (manager(this).isMasterFor(PathUtils.extractParentPath(path)))
        {
            String master = manager(this).getMasterOf(path,true);            
            if (master != null) // verifica no banco local se o diretório já existe
            {
                throw new DirectoryExists(path, master);
            }
            else
            {
                manager(this).createEntryFor(path,masterHostName);
                Log.logDirectoryCreation(path, masterHostName);
                manager(this).notifyMasters(path);
            }
        }
        else
        {
            String master = manager(this).getMasterOf(PathUtils.extractParentPath(path),false); // busca quem é o master em uma busca em largura
            if (master == null) // o master para o diretório não é conhecido pelo servidor local e nenhum dos outros servidores conhecidos
            {
                if (!path.equals("/")) // verifica se o usuário desejou criar um diretório diferente do raiz "/"
                    throw new DirectoryNotFound(PathUtils.extractParentPath(path));
                else // caso seja o raiz e ninguém conheca o master, o servidor toma o controle do "/"
                {
                    manager(this).createEntryFor(path, masterHostName);
                    Log.logDirectoryCreation(path, masterHostName);
                    manager(this).notifyMasters(path);     
                    return;
                }
            }
            else { // o master é conhecido para o diretório pai é conhecido
                manager(this).createEntryFor(path, ConfigurationManager.getBaseConfigInstance().getValue(ServerConfigurationProps.SERVER_HOST_NAME));
                Log.logDirectoryCreation(path, masterHostName);
                manager(this).notifyMasters(path);
                return;
            }
        }
    }

    public IGuid createFile(String filePath) throws RemoteException {
        Log.logNormalOperation(Log.OP_TYPE_CREATE, "Criando arquivo: " + filePath, this);
        String parent = PathUtils.extractParentPath(filePath);
        String master = manager(this).getMasterOf(parent, false);
        String localMaster = ConfigurationManager.getBaseConfigInstance().getValue(ServerConfigurationProps.SERVER_HOST_NAME);
        if (master.equals(localMaster)) {
            IGuid guid = guidFactory.generateGuid(filePath);
            
            // criando os arquivos e suas réplicas
            PeerObjects[] freeServers = FileServerTable.getInstance().getFreeObjects();
            DbFileReplica [] replicas = new DbFileReplica[freeServers.length];
            FastStringArray replicasHostName = new FastStringArray(freeServers.length);
            DbPeerQueries peerQuery = new DbPeerQueries();
            int x = 0;
            for(PeerObjects o: freeServers) {
                Log.debug("Chamando objeto: " + o.getFile().toString());
                o.getFile().createFile(guid);
                DbFileReplica replica = new DbFileReplica();
                replica.setReplicaHost(peerQuery.getPeerByName(o.getHost()));
                replica.setReplicaLastAccess(new java.util.Date(System.currentTimeMillis()));
                replicas[x++] = replica;
                replicasHostName.add(replica.getReplicaHost().getPeerName());
            }
            
            DbFile file = new DbFile();
            file.setFileGuid(guid.toHexString());
            file.setFileName(filePath);
            DbDirectory dir = (new DbDirectoryQueries()).getDirByName(parent);
            file.setParentDir(dir);
            Database.getGridFsDb().storeObjectTree(file);
            for(DbFileReplica r: replicas) {
                r.setFile(file);
                Database.getGridFsDb().storeObjectTree(r);
            }
            
            Log.logFileCreation(guid.toHexString(), master, file.getFileName(), file.getParentDir().getDirName(),replicasHostName.toArray());
            
            return guid;
        }
        else {
            PeerObjects objs = MasterPeerTable.getInstance().getObjectsFor(master);
            IGuid guid = objs.getDirectory().createFile(filePath);
            // caso o arquivo tenha sido criado em outro DM, não precisa fazer o log
            return guid;            
        }
    }

    public void deleteDirectory(String path) throws RemoteException {
        String master = manager(this).getMasterOf(path, false);
        String localMaster = ConfigurationManager.getBaseConfigInstance().getValue(ServerConfigurationProps.SERVER_HOST_NAME);
        
        if (master.equals(localMaster)) {
            String [] contents = listContents(path);
            if (contents.length > 0)
                throw new DirectoryNotEmpty(path, "exclusão");
            else {
                DbDirectoryQueries query = new DbDirectoryQueries();
                DbDirectory dir = query.getDirByName(path);
                Database.getGridFsDb().deleteObject(dir);
                manager(this).notifyMastersDirDeletion(path);
            }
        } else {
                DbDirectoryQueries query = new DbDirectoryQueries();
                DbDirectory dir = query.getDirByName(path);
                Database.getGridFsDb().deleteObject(dir);            
        }
                Log.logDeleteDirectory(path, master);        
    }

    public void deleteFile(String file) throws RemoteException {
        
        String master = manager(this).getMasterOf(PathUtils.extractParentPath(file), false);
        String localMaster = ConfigurationManager.getBaseConfigInstance().getValue(ServerConfigurationProps.SERVER_HOST_NAME);
        DbFile dbFile = (new DbFileQueries()).getByName(file);
        
        if(master.equals(localMaster)) {
            DbReplicaQueries query = new DbReplicaQueries();
            DbPeer [] peers = query.getReplicasByFileName(file);
            for(DbPeer peer: peers) {
                PeerObjects objs = FileServerTable.getInstance().getObjectsFor(peer.getPeerName());
                objs.getFile().deleteFile(guidFactory.generateGuid(dbFile.getFileGuid()));
            }
            
            Log.logDeleteFile(dbFile.getFileGuid(),master);
            
        } else {
            PeerObjects objs = MasterPeerTable.getInstance().getObjectsFor(master);
            objs.getDirectory().deleteFile(file);
        }
        
    }

    public String getDirectoryMaster(String path)  throws RemoteException{
        Log.logNormalOperation(Log.OP_TYPE_QUERY, "master for " + path, this);        
        return manager(this).getMasterOf(path, true); // busca apenas no banco de dados local!       
    }

//    public String getHostForFile(String path)  throws RemoteException{
//        throw new UnsupportedOperationException("Not supported yet.");
//    }

    public void setDirectoryMaster(String path, String hostName)  throws RemoteException{        
        manager(this).createEntryFor(path, hostName);
        Log.logNormalOperation(Log.OP_TYPE_CREATE,hostName + " dm para " + path, this);        
    }
    
//    public boolean requestMasterControlFor(String path)  throws RemoteException{
//        throw new UnsupportedOperationException("Not supported yet.");
//    }
//    
//    public boolean confirmMasterControlFor(String path) throws RemoteException{
//        throw new UnsupportedOperationException("Not supported yet.");        
//    }

    public String[] listContents(String path) throws RemoteException {
        String result[] = null;
        
        DbDirectoryQueries query = new DbDirectoryQueries();
        DbDirectory dir[] = query.listAll(path);
        
        DbFileQueries fileQuery = new DbFileQueries();
        DbFile file[] = fileQuery.getByParent(path);
        
        int x = 0;        
        String dirNames [] = new String[dir.length];
        for(DbDirectory d: dir)
            dirNames[x++] = d.getDirName()+":"+d.getDirOwner().getPeerName();
        
        Filters filter = new Filters();
        String [] filtered = filter.regExpFilter(PathUtils.toDirectoryFilter(path), dirNames, "d:", "", true);
        
        result = new String[filtered.length + file.length];
        System.arraycopy(filtered, 0, result, 0, filtered.length);
        
        x = filtered.length;
        for(DbFile f: file)
            result[x++] = "f:" + f.getFileName();
        
        if (result.length == 0)
            return result;
        
        java.util.Arrays.sort(result,0,result.length-1);
        
        return result;
    }

    public boolean exists(String path) throws RemoteException {
        return manager(this).getMasterOf(path, false) != null;
    }

    public IGuid openFile(String filePath) throws RemoteException {
        DbFileQueries query = new DbFileQueries();
        DbFile file = query.getByName(filePath);
        return guidFactory.generateGuid(ByteToHexConverter.fromHex(file.getFileGuid().toCharArray()));        
    }

    public DbLogEntry[] getLogSince(int year, int dayOfYear, int hour, int minute, int second) throws RemoteException {
        DbLogEntryQueries query = new DbLogEntryQueries();
        return query.getEntries(year, dayOfYear, hour, minute, second, true);
    }

    public DirectoryOperations isAlive() throws RemoteException {
        return this;
    }    
    
    /*
     * Definições static
     * */
    
    private static Hashtable<DirectoryOperationsImpl,IDirectoryManager> managers;
    
    public static void setDirectoryManagerFor(DirectoryOperationsImpl impl, IDirectoryManager manager)
    {
        managers.put(impl, manager);
    }
    
    public static IDirectoryManager manager(DirectoryOperationsImpl impl)
    {
        return managers.get(impl);
    }
    
    static // construtor estático, apenas inicializar a variável managers
    {
        managers = new Hashtable<DirectoryOperationsImpl, IDirectoryManager>();
    }
}
